<?php

namespace App\Http\Controllers\Front;

use App\Interfaces\AreaService;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Services\Rsa;

class ApiClientController extends Controller
{

    public function index(AreaService $areaService)
    {

        return view('front.api_client');

    }

    public function requestOk(Request $request,Rsa $rsa){

        $url = $request->get('url');
        $session_id = $request->get('session_id');
        $param = $request->get('body');


        $encryptedBody = $rsa->encrypt($param);

        $header = [
            "Content-Type"=>"text/plain"
        ];

        if ($session_id!=''){
            $header['session-id']=$session_id;
        }

        $response = $this->makeRequest($url,$header,$encryptedBody);

        return response()->json($response);


    }


    /**
     * 构建请求
     * @param string $data
     * @param string $url
     * @return mixed|string
     */
    private function makeRequest($url,Array $headers, $body)
    {
        foreach( $headers as $n => $v ) {
            $headerArr[] = $n .':' . $v;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt ($ch, CURLOPT_HTTPHEADER , $headerArr );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        $query = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($query, 0, $headerSize);
        $body = substr($query, $headerSize);

        $return  =  ['header'=>$header,'status'=>$httpCode,'body'=>$body];
        return $return;

    }


    private function unicode_decode($name)
    {
        // 转换编码，将Unicode编码转换成可以浏览的utf-8编码
        $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
        preg_match_all($pattern, $name, $matches);
        if (!empty($matches))
        {
            $name = '';
            for ($j = 0; $j < count($matches[0]); $j++)
            {
                $str = $matches[0][$j];
                if (strpos($str, '\\u') === 0)
                {
                    $code = base_convert(substr($str, 2, 2), 16, 10);
                    $code2 = base_convert(substr($str, 4), 16, 10);
                    $c = chr($code).chr($code2);
                    $c = iconv('UCS-2', 'UTF-8', $c);
                    $name .= $c;
                }
                else
                {
                    $name .= $str;
                }
            }
        }
        return $name;
    }
}
